package com.example.service;

import com.example.exception.NoServerException;
import com.example.utils.RandomUtils;
import io.etcd.jetcd.KeyValue;
import io.etcd.jetcd.watch.WatchEvent;
import io.etcd.jetcd.watch.WatchResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class SysClusterServiceImpl implements SysClusterService, InitializingBean, KeyListener {

    private final boolean isServer;
    Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private EtcdService etcdService;

    @Resource
    private SysServerService sysServerService;

    public SysClusterServiceImpl(boolean isServer) {
        this.isServer = isServer;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (this.isServer) {
            this.etcdService.putAutoLease(ROOT_PATH + sysServerService.getServerKey(), sysServerService.getServerKey().getBytes(StandardCharsets.UTF_8), 1);
        }
        this.etcdService.watchPrefKey(ROOT_PATH, this);
    }

    @Override
    public void onNext(WatchResponse watchResponse) {
        List<WatchEvent> events = watchResponse.getEvents();
        for (WatchEvent event : events) {
            //加入到了集群
            if (event.getEventType() == WatchEvent.EventType.PUT) {
                logger.warn("集群节点: " + event.getKeyValue().getKey().toString(StandardCharsets.UTF_8) + " 加入了集群");
            }
            //离开了集群
            if (event.getEventType() == WatchEvent.EventType.DELETE) {
                logger.warn("集群节点: " + event.getKeyValue().getKey().toString(StandardCharsets.UTF_8) + " 离开了集群");
            }
        }
    }

    /****
     * 获取随机一个主节点
     * @return
     */
    @Override
    public String getServer() throws Exception {
        List<String> serverList = getServerList();
        if (serverList.isEmpty()) {
            throw new NoServerException("当前不存在活跃的服务节点 ...");
        }
        return serverList.get(RandomUtils.getRandomInt(serverList.size()));
    }


    /***
     * 获取主节点列表
     * @return
     */
    @Override
    public List<String> getServerList() throws Exception {
        List<String> serverList = new ArrayList<>();
        for (KeyValue keyValue : this.etcdService.getChildList(ROOT_PATH)) {
            serverList.add(keyValue.getValue().toString(StandardCharsets.UTF_8));
        }
        return serverList;
    }
}
